unit GuardProcessMainUnit;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, TlHelp32, StdCtrls, ExtCtrls, ShellAPI;

type
  TForm1 = class(TForm)
    ListBox1: TListBox;
    Button1: TButton;
    Timer: TTimer;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure TimerTimer(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
  private
    { Private declarations }
    FGuardList: TStrings;
    procedure RecurseProcess(ASL: TStrings);
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

procedure ParseLine(ALine: string; ADelimiter: Char; AStrings: TStrings);
var
  I: Integer;
  szTemp: string;
begin
  if ALine = '' then Exit;
  AStrings.Clear( );
  szTemp := ALine;
  I := Pos(ADelimiter, szTemp);
  while I <> 0 do
  begin
    AStrings.Add( copy (szTemp, 1, I - 1));
    Delete(szTemp, 1, I);
    I := Pos(ADelimiter, szTemp);
  end;
  AStrings.Add(szTemp);
end;

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
begin

    
  Width := 0;
  Height := 0;
  Top := -1000;
  Left := -1000;

  SetWindowLong(Application.Handle, GWL_EXSTYLE, WS_EX_TOOLWINDOW);

  FGuardList := TStringList.Create;

  if ParamCount > 0 then
  begin
//    FGuardList.CommaText :=  ParamStr(1);
    ParseLine(ParamStr(1), ',', FGuardList);
    Timer.Interval := 5000;
  end
  else
  begin
    with TStringList.Create do
    try
      LoadFromFile(ExtractFilePath(ParamStr(0)) + 'Guard.cfg');
//      FGuardList.CommaText := Values['GuardList'];
      ParseLine(Values['GuardList'], ',', FGuardList);
      Timer.Interval := StrToIntDef(Values['TimeInterval'], 5) * 1000;
    finally
      Free;
    end;

  end;

  if FGuardList.Count = 0 then
    Application.Terminate;
end;

procedure TForm1.RecurseProcess(ASL: TStrings);
var
//  P: ProcessInfo;
  Ret: Bool;
  ProcessListHandle: THandle;
  ProcessStruct: TProcessEntry32;
begin
  ProcessListHandle := CreateToolHelp32Snapshot(TH32CS_SnapProcess, 0);
  ProcessStruct.dwSize := SizeOf( ProcessStruct );
  Ret := Process32First( ProcessListHandle, ProcessStruct );
  while (Ret) do
  begin
    ASL.Add( ProcessStruct.szExeFile );
    Ret := Process32Next( ProcessListHandle, ProcessStruct );
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  RecurseProcess( ListBox1.Items );
end;

procedure TForm1.TimerTimer(Sender: TObject);
var
  SL: TStrings;
  i: Integer;
begin
  SL := TStringList.Create;
  try
    RecurseProcess(SL);

    for i := 0 to FGuardList.Count - 1 do
      if SL.IndexOf(ExtractFileName(FGuardList[i])) < 0 then
        ShellExecute(0, 'open', PChar(FGuardList[i]), nil, nil, SW_HIDE);
  finally
    SL.Free;
  end;

end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  FGuardList.Free;
end;

end.
